package com.example.kingweather.fragment;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.kingweather.R;
import com.example.kingweather.adapter.WeatherGridAdapter;
import com.example.kingweather.bean.AirBean;
import com.example.kingweather.bean.WeatherBean;
import com.example.kingweather.utils.HttpUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import androidx.fragment.app.Fragment;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;

import static android.content.ContentValues.TAG;

public class WeatherFragment extends Fragment {
    @BindView(R.id.grid_view_daily_forecast)
    GridView gridViewDailyForecast;
    @BindView(R.id.line_chart_weather_tmp)
    LineChart lineChartWeatherTmp;
    private Unbinder unbinder;

    @BindView(R.id.text_location)
    TextView textLocation;
    @BindView(R.id.text_date_time)
    TextView textDateTime;
    @BindView(R.id.text_tmp)
    TextView textTmp;
    @BindView(R.id.text_wind)
    TextView textWind;
    @BindView(R.id.text_air)
    TextView textAir;
    @BindView(R.id.image_cond)
    ImageView imageCond;
    @BindView(R.id.text_cond_txt)
    TextView textCondTxt;
    @BindView(R.id.list_view_weather)


    ListView listViewWeather;
    private String location = "潮州";
    private ScheduledExecutorService serviceSetNowTime;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_weather, container, false);
        serviceSetNowTime = Executors.newScheduledThreadPool(1);
        unbinder = ButterKnife.bind(this, view);

        setNowTime();

        setWeather();

        setAir();


        return view;
    }


    /**
     * 显示系统时间，并且每个60秒更新一次
     */
    private void setNowTime() {
        serviceSetNowTime.scheduleAtFixedRate(() -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = new Date(System.currentTimeMillis());
            getActivity().runOnUiThread(() -> textDateTime.setText(format.format(date)));
        }, 0, 6000, TimeUnit.MILLISECONDS);
    }


    /**
     * 设置天气信息
     */
    private void setWeather() {
        HttpUtils.getHttpUtils().getNowWeather(location)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WeatherBean>() {

                    private List<Entry> mimTmpList;
                    private List<Entry> maxTmpList;
                    private WeatherGridAdapter weatherGridAdapter;

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onNext(WeatherBean nowWeatherBean) {




                        textLocation.setText(location);

                        textCondTxt.setText(nowWeatherBean.getHeWeather6().get(0).getNow().getCond_txt());
                        textWind.setText(nowWeatherBean.getHeWeather6().get(0).getNow().getWind_dir() + " "
                                + nowWeatherBean.getHeWeather6().get(0).getNow().getWind_sc() + "级" + " "
                                + nowWeatherBean.getHeWeather6().get(0).getNow().getWind_spd() + "km/h");
                        textTmp.setText(nowWeatherBean.getHeWeather6().get(0).getNow().getTmp() + "°");


                        weatherGridAdapter = new WeatherGridAdapter(getActivity(), nowWeatherBean.getHeWeather6().get(0).getDaily_forecast());
                        gridViewDailyForecast.setHorizontalSpacing(0);
                        gridViewDailyForecast.setAdapter(weatherGridAdapter);
/*------------------------------------------------------------------------------------------------------*/
                                /*温度图表*/
                        maxTmpList = new ArrayList<>();
                        mimTmpList = new ArrayList<>();

                        for (int i = 0; i < nowWeatherBean.getHeWeather6().get(0).getDaily_forecast().size(); i++) {
                            maxTmpList.add(new Entry(i, Integer.parseInt(nowWeatherBean.getHeWeather6()
                                    .get(0).getDaily_forecast().get(i).getTmp_max())));
                            mimTmpList.add(new Entry(i, Integer.parseInt(nowWeatherBean.getHeWeather6()
                                    .get(0).getDaily_forecast().get(i).getTmp_min())));
                            Log.e(TAG, "onNext: "+mimTmpList.get(i) );
                        }

                        lineChartWeatherTmp.getAxisLeft().setEnabled(false);
                        lineChartWeatherTmp.getAxisLeft().setDrawGridLines(false);
                        lineChartWeatherTmp.getAxisRight().setEnabled(false);
                        lineChartWeatherTmp.getXAxis().setEnabled(false);
                        lineChartWeatherTmp.getDescription().setEnabled(false);
                        lineChartWeatherTmp.getLegend().setEnabled(false);

                        LineDataSet dataSetMax = new LineDataSet(maxTmpList, "");
                        dataSetMax.setColor(Color.RED);
                        dataSetMax.setDrawCircleHole(false);
                        dataSetMax.setCircleColor(Color.RED);
                        LineDataSet dataSetMin = new LineDataSet(mimTmpList, "");
                        dataSetMin.setColor(Color.BLUE);
                        dataSetMin.setDrawCircleHole(false);
                        dataSetMin.setCircleColor(Color.BLUE);

                        LineData lineData = new LineData(dataSetMax, dataSetMin);
                        lineData.setValueTextSize(14);

                        lineData.setValueFormatter(new ValueFormatter() {
                            @Override
                            public String getFormattedValue(float value) {
                                return value + "℃";
                            }


                        });

                        lineChartWeatherTmp.setTouchEnabled(false);
                        lineChartWeatherTmp.setData(lineData);
                        lineChartWeatherTmp.invalidate();
/*-------------------------------------------------------------------------------------------------------*/
                    }
                });
    }


    private void setAir() {
        HttpUtils.getHttpUtils().getNowAir(location)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AirBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(AirBean airBean) {
                        textAir.setText("空气质量  " + airBean.getHeWeather6().get(0).getAir_now_city().getQlty());
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        serviceSetNowTime.shutdownNow();
    }


}

